/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dale2507.gates;

import dale2507.gates.events.ChevronDialledEvent;
import dale2507.gates.events.GateActivateEvent;
import dale2507.gates.events.GateDeactivateEvent;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.getspout.spoutapi.SpoutManager;
import org.getspout.spoutapi.player.SpoutPlayer;
import org.getspout.spoutapi.sound.SoundManager;

/**
 *
 * @author Dale
 */
class SpoutDialSounds implements Listener {
    
    private SoundManager soundManager;
    private String ACTIVATE_URL = "https://sites.google.com/site/dale2507/activate.ogg";
    private String DEACTIVATE_URL = "https://sites.google.com/site/dale2507/deactivate.ogg";
    private String CHEVRON_URL = "https://sites.google.com/site/dale2507/chevron.ogg";
    
    SpoutDialSounds() {
        soundManager = SpoutManager.getSoundManager();
        Bukkit.getPluginManager().registerEvents(this, GatePlugin.getInstance());
        
        Logger.getLogger(SpoutDialSounds.class.getName()).log(Level.INFO, "Spout audio initialised");
    }
    
    private void playSound(String url, Location... locs) {
        if (locs.length > 0) {
            for (SpoutPlayer p : SpoutManager.getOnlinePlayers()) {
                Location location = locs[0];
                double distance = location.distanceSquared(p.getLocation());
                for (Location l : locs) {
                    double dist2 = l.distanceSquared(p.getLocation());
                    if (dist2 < distance) {
                        location = l;
                        distance = dist2;
                    }
                }

                soundManager.playCustomMusic(GatePlugin.getInstance(), p, url, false, location);
            }
        }
    }
    
    @EventHandler(priority = EventPriority.NORMAL)
    public void onChevronDial(ChevronDialledEvent event) {
        this.playSound(CHEVRON_URL, event.getGate().getRing().getExit());
    }
    
    @EventHandler(priority = EventPriority.NORMAL)
    public void onGateActivateEvent(GateActivateEvent event) {
        this.playSound(ACTIVATE_URL, event.getSource().getRing().getExit(), event.getDestination().getRing().getExit());
    }
    
    @EventHandler(priority = EventPriority.NORMAL)
    public void onGateDeactivateEvent(GateDeactivateEvent event) {
        this.playSound(DEACTIVATE_URL, event.getSource().getRing().getExit(), event.getDestination().getRing().getExit());
    }
    
}
